
var User = require('../proxy').User;
var Topic = require('../proxy').Topic;
var Reply = require('../proxy').Reply;
var TopicCollect = require('../proxy').TopicCollect;
var utility = require('utility');
var util = require('util');
var TopicModel = require('../models').Topic;
var ReplyModel = require('../models').Reply;

var tools = require('../common/tools');
var config = require('../config');
var EventProxy = require('eventproxy');
var validator = require('validator');
var utility = require('utility');
var _ = require('lodash');
var qrcode = require('yaqrcode');
var S = require('string');

exports.index = function (req, res, next) {
  var opt = {limit: 100, sort: '-score'};
  User.getUsersByQuery({'$or': [
    {is_block: {'$exists': false}},
    {is_block: false},
    {is_block: true},
  ]}, opt, function (err, tops) {
    if (err) {
      return next(err);
    }
    res.render('usermanager/index', {
      users: tops,
      user_roles: config.user_roles,
      departments: config.departments,
      pageTitle: '账号查询',
    });
  });
};

exports.create = function (req, res, next) {
  var departments = config.departments;
  var user_roles = config.user_roles;
  res.render('usermanager/create', {
    departments: departments,
    user_roles: user_roles
  })
};

exports.createPost = function (req, res, next) {

  var loginname = validator.trim(req.body.loginname).toLowerCase();
  var email = validator.trim(req.body.email).toLowerCase();
  var pass = validator.trim(req.body.pass);
  var rePass = validator.trim(req.body.re_pass);
  var department_code = validator.trim(req.body.department_code);
  var user_role_code = validator.trim(req.body.user_role_code);
  var phone = validator.trim(req.body.phone) || '';
  var position = validator.trim(req.body.position) || '';

  var ep = new EventProxy();
  ep.fail(next);
  ep.on('prop_err', function(msg) {
      res.status(422);
      res.render('usermanager/create', {
          error: msg,
          loginname: loginname,
          email: email
      });
  });

  var emailObj = S(email);
  var isAllowedDomainEmail = false;
  config.org_domains.forEach(function(d) {
      if (emailObj.contains('@' + d)) isAllowedDomainEmail = true
  });

  if (!isAllowedDomainEmail) {
      ep.emit('prop_err', '该邮箱不属于有效域名，不允许注册账号。');
      return;
  }


  // 验证信息的正确性
  if ([loginname, pass, rePass, email].some(function(item) {
          return item === '';
      })) {
      ep.emit('prop_err', '信息不完整。');
      return;
  }
  if (loginname.length < 5) {
      ep.emit('prop_err', '用户名至少需要5个字符。');
      return;
  }
  if (!tools.validateId(loginname)) {
      return ep.emit('prop_err', '用户名不合法。');
  }
  if (!validator.isEmail(email)) {
      return ep.emit('prop_err', '邮箱不合法。');
  }
  if (pass !== rePass) {
      return ep.emit('prop_err', '两次密码输入不一致。');
  }
  // END 验证信息的正确性


  User.getUsersByQuery({
      '$or': [{
          'loginname': loginname
      }, {
          'email': email
      }]
  }, {}, function(err, users) {
      if (err) {
          return next(err);
      }
      if (users.length > 0) {
          ep.emit('prop_err', '用户名或邮箱已被使用。');
          return;
      }

      tools.bhash(pass, ep.done(function(passhash) {
          // create gravatar
          var avatarUrl = User.makeGravatar(email);
          User.newAndSave(loginname, loginname, passhash, email, avatarUrl, true, department_code, user_role_code, phone, position, function(err) {
              if (err) {
                  return next(err);
              }
              // 发送激活邮件
              // mail.sendActiveMail(email, utility.md5(email + passhash + config.session_secret), loginname);
              res.render('usermanager/create', {
                  success: '账号创建成功： ' + loginname
              });
          });

      }));
  });
};


exports.edit = function (req, res, next) {
  var departments = config.departments;
  var user_roles = config.user_roles;

  User.getUserById(req.params.id, function (err, user) {
    if (err) {
      return next(err);
    }

    user.departments = departments;
    user.user_roles = user_roles;
    return res.render('usermanager/edit', user)
  });

};

exports.editPost = function (req, res, next) {
  var departments = config.departments;
  var user_roles = config.user_roles;

  var pass = validator.trim(req.body.pass);
  var rePass = validator.trim(req.body.re_pass);
  var is_block = validator.trim(req.body.is_block);
  var department_code = validator.trim(req.body.department_code);
  var user_role_code = validator.trim(req.body.user_role_code);
  var phone = validator.trim(req.body.phone) || '';
  var position = validator.trim(req.body.position) || '';
  var is_change_password = validator.trim(req.body.is_change_password) || '';
  if (!is_change_password) {
    pass = '';
    rePass = '';
  }

  var ep = new EventProxy();
  ep.fail(next);
  ep.on('prop_err', function(msg) {
      res.status(422);
      var user = req.body;
      user._id = req.params.id;
      user.departments = departments;
      user.user_roles = user_roles;
      user.error = msg;
      res.render('usermanager/edit', user);
  });

  // var emailObj = S(email);
  // var isAllowedDomainEmail = false;
  // config.org_domains.forEach(function(d) {
  //     if (emailObj.contains('@' + d)) isAllowedDomainEmail = true
  // });

  // if (!isAllowedDomainEmail) {
  //     ep.emit('prop_err', '该邮箱不属于有效域名，不允许注册账号。');
  //     return;
  // }


  // 验证信息的正确性
  // if ([loginname, pass, rePass, email].some(function(item) {
  //         return item === '';
  //     })) {
  //     ep.emit('prop_err', '信息不完整。');
  //     return;
  // }
  // if (loginname.length < 5) {
  //     ep.emit('prop_err', '用户名至少需要5个字符。');
  //     return;
  // }
  // if (!tools.validateId(loginname)) {
  //     return ep.emit('prop_err', '用户名不合法。');
  // }
  // if (!validator.isEmail(email)) {
  //     return ep.emit('prop_err', '邮箱不合法。');
  // }
  if (pass !== '') {
    if (pass !== rePass) {
      return ep.emit('prop_err', '两次密码输入不一致。');
    }
  }
  if ([department_code, user_role_code].some(function(item) {
          return item === '';
      })) {
      ep.emit('prop_err', '信息不完整。');
      return;
  }

  User.getUserById(req.params.id, ep.done(function (user) {
    user.user_roles = user_roles;
    user.departments = departments;

    user.is_block = is_block;
    user.department_code = department_code;
    user.user_role_code = user_role_code;
    user.phone = phone;
    user.position = position;
    if ( pass !== '' ){
      //change password
      tools.bhash(pass, ep.done(function (passhash) {
        user.pass = passhash;
        user.save(function (err) {
          if (err) {
            return next(err);
          }
          user.success = '保存用户成功，密码已被修改。';
          return res.render('usermanager/edit', user);
        });
      }));
    } else {
      user.save(function (err) {
        if (err) {
          return next(err);
        }
        user.success = '保存用户成功。';
        return res.render('usermanager/edit', user);
      });
    }

  }));
};
